# -*- coding: utf-8 -*-
"""
Web framework/Tornado Escape/test01.py
"""
import tornado.escape
import tornado.web
import asyncio


class XhtmlEscapeHandler(tornado.web.RequestHandler):
    """
    tornado.escape.xhtml_escape
    """

    def get(self):
        p_args = self.get_argument("char")
        p_escape_args = tornado.escape.xhtml_escape(p_args)
        self.finish(p_escape_args)
    # > curl http://127.0.0.1:8888/xhtml_escape?char=">>>999"
    # > HTTP Response: &gt;&gt;&gt;999


class XhtmlUnescapeHandler(tornado.web.RequestHandler):
    """
    tornado.escape.xhtml_unescape
    """

    def get(self):
        p_args = self.get_argument("char")
        p_unescape_args = tornado.escape.xhtml_unescape(p_args)
        self.finish(p_unescape_args)
    # > curl http://127.0.0.1:8888/xhtml_unescape?char="%3B44"
    # > HTTP Response: ;44


class UrlEscapeHandler(tornado.web.RequestHandler):
    """
    tornado.escape.url_escape
    """

    def get(self):
        p_args = self.get_argument("char")
        p_escape_args = tornado.escape.url_escape(p_args)
        self.finish(p_escape_args)
    # > curl http://127.0.0.1:8888/url_escape?char="http://127.0.0.1:8888/"
    # > HTTP Response: http%3A%2F%2F127.0.0.1%3A8888%2F


class UrlUnescapeHandler(tornado.web.RequestHandler):
    """
    tornado.escape.url_unescape
    """

    def get(self):
        p_args = self.get_argument("char")
        p_unescape_args = tornado.escape.url_unescape(p_args)
        self.finish(p_unescape_args)
    # > curl http://127.0.0.1:8888/url_unescape?char="http%3A%2F%2F127.0.0.1%3A8888%2Fhttp://127.0.0.1:8888/"
    # > HTTP Response: http://127.0.0.1:8888/http://127.0.0.1:8888/


class JsonEncodeHandler(tornado.web.RequestHandler):
    """
    tornado.escape.json_encode
    """

    def get(self):
        p_args = self.get_argument("char")
        o_res = {
            "param": p_args
        }
        o_json = tornado.escape.json_encode(o_res)
        self.finish(o_json)
    # > curl http://127.0.0.1:8888/json_encode?char=123
    # > HTTP Response: {"param": "123"}


class JsonDecodeHandler(tornado.web.RequestHandler):
    """
    tornado.escape.json_decode
    """

    def post(self):
        p_json = self.request.body
        o_res = tornado.escape.json_decode(p_json)
        j_keys = o_res.keys()
        self.finish(str(j_keys))
    # curl -X POST -H "Content-Type: application/json" -s "http://127.0.0.1:8888/json_decode"
    # -d "{\"name\": \"Mack\", \"age\": 20}"
    # HTTP Response: dict_keys(['name', 'age'])


async def main():
    app = tornado.web.Application([
        (r'/xhtml_escape', XhtmlEscapeHandler),
        (r'/xhtml_unescape', XhtmlUnescapeHandler),
        (r'/url_escape', UrlEscapeHandler),
        (r'/url_unescape', UrlUnescapeHandler),
        (r'/json_encode', JsonEncodeHandler),
        (r'/json_decode', JsonDecodeHandler),
    ])
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(main())
